package com.heiye.blog.ai.helper;

import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Lists;
import com.heiye.blog.ai.advisor.impl.CustomChatMemoryAdvisor;
import com.heiye.blog.ai.advisor.impl.CustomStreamLoggerAndMessage2DBAdvisor;
import com.heiye.blog.ai.advisor.impl.NetworkSearchAdvisor;
import com.heiye.blog.ai.domain.mapper.ChatMessageMapper;
import com.heiye.blog.ai.model.dto.AIChatRequest;
import com.heiye.blog.ai.model.vo.AiChatReqVO;
import com.heiye.blog.ai.servie.SearXNGService;
import com.heiye.blog.ai.servie.SearchResultContentFetcherService;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.Collections;
import java.util.List;

/**
 * @author: heiye
 * @date: 2025/11/07 下午8:37
 * @version: v1.0.0
 * @description: Advisor 辅助类
 */
@Component
public class AdvisorHelper {

    @Resource
    private ChatMessageMapper chatMessageMapper;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private SearXNGService searXNGService;

    @Resource
    private SearchResultContentFetcherService searchResultContentFetcherService;

    /**
     * 构建 Advisor 集合
     *
     * @param aiChatRequest
     * @return
     */
    public List<Advisor> buildAdvisors(AIChatRequest aiChatRequest) {
        // 是否需要联网搜索
        Boolean networkSearch = aiChatRequest.getNetworkSearch();
        // 创建 Advisor 集合，判断 AIChatRequest 里是否已经有 Advisor，如果没有则创建一个空的
        List<Advisor> advisors = CollUtil.isNotEmpty(aiChatRequest.getAdvisors()) ?
                aiChatRequest.getAdvisors() : Lists.newArrayList();

        // 是否开启了联网搜索
        if (networkSearch) {
            advisors.add(new NetworkSearchAdvisor(searXNGService, searchResultContentFetcherService));
        } else {
            // 添加自定义对话记忆 Advisor（以最新的 50 条消息作为记忆）
            advisors.add(new CustomChatMemoryAdvisor(chatMessageMapper, aiChatRequest, 50));
        }

        // 添加自定义打印流式对话日志 Advisor
        advisors.add(new CustomStreamLoggerAndMessage2DBAdvisor(chatMessageMapper, aiChatRequest, transactionTemplate));
        return advisors;
    }
}
